import React, { Fragment, useEffect, useState } from 'react'
import '@/style/main/main.scss'
import TableItem from './TableItem'
import SimpleMDE from "react-simplemde-editor";
import "easymde/dist/easymde.min.css";
import useIpcRenderer from 'hooks/useIpcRenderer';
import useKeyPress from 'hooks/useKeyPress';
import { timestampToString } from 'utils/helper';
import Loading from 'components/common/Loading';

export default function Main({ openFiles, activeID, unsaveIDs, activeFile, setActiveFileID, tabCLose, fileChange, saveCurrentFile }) {
    const sPress = useKeyPress(83)
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        const oEvent = window.event;
        if (sPress && oEvent.ctrlKey) { // 按下ctrl+s组合键保存文件
            saveCurrentFile()
        }
    })

    useIpcRenderer({
      'loading-status': (event, status) =>{
          console.log('xxxx');
          setLoading(status)
      },
    })

    const judgeLoading = () => {
        if (loading) {
            return <Loading />
        }

        return openFiles.length ?
            <Fragment>
                <div className='main-nav'>
                    {
                        openFiles.length > 0 && openFiles.map((item, index) => {
                            return <TableItem
                                file={item}
                                key={index}
                                activeID={activeID}
                                onTabClick={(id) => { setActiveFileID(id); }}
                                onCloseTab={(id) => { tabCLose(id) }}
                                unsaveIds={unsaveIDs}
                            />
                        })
                    }
                </div>
                {
                    activeID && <SimpleMDE
                        key={activeFile && activeFile.id}
                        value={activeFile && activeFile.body}
                        onChange={(value) => { fileChange(activeFile.id, value); }}
                        options={{
                            minHeight: `${document.body.clientHeight - 190}px`,
                        }}
                    />
                }
                {
                    activeFile.isSynced &&
                    <div className='main-synced'>已同步，上次同步时间：{timestampToString(activeFile.updatedAt)}</div>
                }
            </Fragment> :
            <div className='main-start-page'>选择或创建新的 Markdown 文档</div>
    }
    return (
        <div className='main'>
            {
                judgeLoading()
            }
        </div>
    )
}
